package com.crois.barrier.admin.server;

import com.crois.barrier.admin.entity.BarrierServer;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Hou Ze Yu
 * @description 服务列表管理
 * @date 2020/10/23
 */
@Component
public class ServerListManager {

    private final Object putSeverLock = new Object();

    private final Object updateServiceLock = new Object();



    /***
     * serverMap
     */
    private Map<String, BarrierServer> serverMap = new ConcurrentHashMap<>(200);



    /**
     * get server
     * @param address
     * @return
     */
    public BarrierServer getServer(String address){
         if (serverMap.containsKey(address)){
              return serverMap.get(address);
         }
         return null;
    }
    /**
     * get server list
     * @return
     */
    public List<BarrierServer> getServerList(){
        List<BarrierServer> serverList =new ArrayList<>();
        Set<Map.Entry<String, BarrierServer>> entries = serverMap.entrySet();
        for (Map.Entry<String, BarrierServer> entry : entries) {
            BarrierServer value = entry.getValue();
            if (value.isEnabled()){
                serverList.add(value);
            }
        }
        return serverList;
    }


    /**
     * remove server
     * @param address
     */
    public void removeServer(String address){
        if (serverMap.containsKey(address)){
            serverMap.remove(address);
        }
    }

    /**
     * add server
      * @param address
     * @param server
     */
    public void putServer(String address,BarrierServer server){

        if (!serverMap.containsKey(address)){
            synchronized (putSeverLock){
                if (!serverMap.containsKey(address)){
                    serverMap.put(address,server);
                }
            }
        }
    }

    /**
     * update server
     * @param address
     * @param server
     */
    public void updateServer(String address,BarrierServer server){
        synchronized (updateServiceLock){
                serverMap.put(address,server);
        }
    }
}
